<?php
/**
 *
 * 作    者：安德玛
 * 版本控制：20210203===新发布任务默认置顶一天功能
 * 功能说明：任务大厅控制器。
 *
 **/
namespace Api\Controller;

class TaskController extends ComController
{   
    /**
     * 顶部搜索条件
     */
    public function topSelect()
    {
        if(!IS_GET){
            $this->res['code'] = 100;
            $this->res['msg'] = '请使用GET请求方式';
            $this->response($this->res,'json');
        }
        $category_list = M('category')->order('o asc')->field('id,title')->select();
        $user_level_list = M('user_level')->where('is_r=1')->order('o asc')->field('id,title')->select();
        $this->res['msg'] = 'success';
        $this->res['data']['category_list'] = $category_list;
        $this->res['data']['user_level_list'] = $user_level_list;
        $this->response($this->res, 'json');
    }
    
    
    /**
     * 大厅任务列表
     */
    public function item()
    {
        if(!IS_GET){
            $this->res['code'] = 101;
            $this->res['msg'] = '请使用get方法';
            $this->response($this->res,'json');
        }
        $cid = I('get.cid','','htmlentities');
        $level = I('get.level','','htmlentities');
        $sort = I('get.sort','','htmlentities');
        $p = isset($_GET['p']) ? intval($_GET['p']) : '1';
        $pagesize = intval(isset($_GET['pagesize']) ? intval($_GET['pagesize']) : '20');
        
        $model = M();
        $sqlWhere = "a.pay_status=1 and ";
        if($cid){
            $sqlWhere .= "a.cid=".$cid." and ";
        }
        if($level){
            $sqlWhere .= "a.user_level=".$level." and ";
        }
        if($this->user['id']){
			$s = 0;
			$l = 2;
            $notIdArr = M('user_task')->where(array('uid'=>$this->user['id'],'status'=>array('between',array($s,$l))))->field('task_id')->select();
            if(!empty($notIdArr)){
                $notIdArr2 = array_column($notIdArr,'task_id');
                $sqlWhere .= "a.id not in (".implode(',', $notIdArr2).") and ";
            }
        }
        $sqlWhere = msubstr($sqlWhere, 0, utf8_strlen($sqlWhere) - 4, "utf-8", false);
        $orderBy = "a.on_top desc,a.t desc";
        if($sort){
            // $orderBy = "a.on_top desc,a.price ".$sort.",a.t desc";
			$orderBy = "a.on_top desc,"."a.price ".$sort.",a.t desc";
        }
        $offset = $pagesize * ($p - 1);//计算记录偏移量
        $count = $model->query("select count(*) as total,case when date_format(a.end_t,'%Y-%m-%d') < date_format(now(),'%Y-%m-%d') and a.hasdid_num < a.num
                                then 3 when a.hasdid_num>=a.num then 2 else 1 end as `status` from ".C('DB_PREFIX')."task a left join
                                ".C('DB_PREFIX')."category b on a.cid=b.id where ".$sqlWhere);
        $count = intval($count[0]['total']);
        $sql = "select a.*,b.title as category_title,b.icon,case when date_format(a.end_t,'%Y-%m-%d') < date_format(now(),'%Y-%m-%d') and a.hasdid_num < a.num
                then 3 when a.hasdid_num>=a.num then 2 else 1 end as `status` from ".C('DB_PREFIX')."task a left join ".C('DB_PREFIX')."category b
                on a.cid=b.id where ".$sqlWhere." order by ".$orderBy." limit ".$offset . "," . $pagesize;
        $list = $model->query($sql);
        foreach ($list as $k=>&$v){
			
            // 允许接单会员等级
            $user_level = $v['user_level'];
            $info = M('user_level')->where('id='.$user_level)->field('title,bg_color')->find();
            $list[$k]['level_info'] = $info['title'];
            $list[$k]['bg_color'] = $info['bg_color'];
            // 任务要求
            $money_type = $v['money_type'];
            $money_type_arr = explode(',', $money_type);
            $money_info_title = '';
            foreach ($money_type_arr as $h=>&$l){
                $money_info = M('money_type')->where('id='.$l)->field('title')->find();
                $money_info_title .= $money_info['title'].' ';
            }
            $list[$k]['money_info'] = $money_info_title;
            // 发布人
            if($v['uid'] == 0){
                $list[$k]['author'] = '平台';
            }else{
                $user = M('user')->where('id='.$v['uid'])->find();
                $list[$k]['author'] = $user['nickname'];
			//增加用户置顶时间逻辑
				$date1 = date('Y-m-d',$v['t']);
				$date2 = date('Y-m-d',time());
				$time_old = date_create($date1);
				$time_new = date_create($date2);
				$interval = date_diff($time_old, $time_new);
				$days = $interval->format('%R%a');
				$list[$k]['test'] = $days;
				if($days > 1){
					$list[$k]['on_top'] = 1;
				}
            }
            // 平台icon
            $list[$k]['icon'] = C('URL').$v['icon'];
            // 当前用户是否已领取任务标识
            $tnum = M('user_task')->where(array('task_id'=>$v['id'],'uid'=>$this->user['id']))->count(); 
            $is_receive = 0;
            if($tnum > 0){
                $is_receive = 1;
            }
            $list[$k]['is_receive'] = $is_receive;
            
        }
        $page = new \Think\Page($count, $pagesize);
        $page->show();
        $page_arr = array(
            'totalCount'=>intval($count),
            'pageSize'=>$pagesize,
            'totalPage'=>$page->totalPages,
            'currPage'=>intval($p)
        );
        $this->res['data']['page'] = $page_arr;
        $this->res['data']['list'] = $list;
        $this->response($this->res,'json');
    }
    
    
    /**
     * 领取任务接口
     */
    public function receiveTask()
    {
        $id = I('get.id','','htmlentities');
        if(!$id){
            $this->res['code'] = 101;
            $this->res['msg'] = '传入任务id为空';
            $this->response($this->res,'json');
        }
        $task = M('task')->where('id='.$id)->find();
        if(empty($task)){
            $this->res['code'] = 102;
            $this->res['msg'] = '该任务不存在';
            $this->response($this->res,'json');
        }
        if(strtotime($task['end_t']) < time()){
            $this->res['code'] = 103;
            $this->res['msg'] = '任务已过期';
            $this->response($this->res,'json');
        }
        if(intval($task['hasdid_num']) >= intval($task['num'])){
            $this->res['code'] = 104;
            $this->res['msg'] = '任务数量已完成';
            $this->response($this->res,'json');
        }
        // 判断会员等级是否满足接单条件
        $user_level = M('user')->where('id='.$this->user['id'])->field('level_id,expri_day')->find();
        $task_level = $task['user_level'];
        $level_id = $user_level['level_id'];

        $level_info = M('user_level')->where(array('id'=>$level_id))->find();
        $task_level_info = M('user_level')->where(array('id'=>$task_level))->find();
        
        if(intval($level_info['o']) < intval($task_level_info['o']) || strtotime($user_level['expri_day']) < time() || $level_info['is_r'] == 0){
            $this->res['code'] = 105;
            $this->res['msg'] = '无此任务权限，请充值会员再试';
            $this->response($this->res,'json');
        }
        // 判断用户当天任务数是否已经完成
        $day_num = intval($level_info['day_num']);
        $s = strtotime(date('Y-m-d').'00:00:00');
        $l = strtotime(date('Y-m-d').'23:59:59');
        $day_finifh_num = M('user_task')->where(array('uid'=>$this->user['id'],'t'=>array('between',array($s,$l))))->count();
        if($day_finifh_num >= $day_num){
            $this->res['code'] = 106;
            $this->res['msg'] = '您每日任务数已完成，请明日再来吧！';
            $this->response($this->res,'json');
        }
        $count = M('user_task')->where(array('uid'=>$this->user['id'],'task_id'=>$id,'status'=>array('in',['0,1,2'])))->count();
        if($count > 0){
            $this->res['code'] = 107;
            $this->res['msg'] = '请勿重复接单！';
            $this->response($this->res,'json');
        }
        
        // 插入用户任务表
        $data = array(
            'task_id'=>$id,
            'uid'=>$this->user['id'],
            'price'=>$task['price'],
            'status'=>0,
            't'=>time()
        );
        $model1 = M('user_task');
        $model2 = M('task');
        
        $model1->startTrans();
        
        $res1 = $model1->data($data)->add();
        $res2 = $model2->where('id='.$task['id'])->setInc('hasdid_num',1);
        
        if($res1 && $res2){
            $model1->commit();
            $this->res['data'] = $res1;
            $this->res['msg'] = '接单成功，待完成处提交任务';
            $this->response($this->res,'json');
        }else{
            $model1->rollback();
            $this->res['code'] = 500;
            $this->res['msg'] = '接单失败';
            $this->response($this->res,'json');
        }
    }
    
    /**
     * 任务详情
     */
    public function taskShow()
    {
        $id = I('get.id','','htmlentities');
        if(!$id){
            $this->res['code'] = 101;
            $this->res['msg'] = '传入任务id为空';
            $this->response($this->res,'json');
        }
        $info = M('task')->where('id='.$id)->find();
        if(empty($info)){
            $this->res['code'] = 102;
            $this->res['msg'] = '该任务不存在';
            $this->response($this->res,'json');
        }
        // 允许接单会员等级
        $user_level = M('user_level')->where('id='.$info['user_level'])->find();
        $info['level_info'] = $user_level['title'];
        // 获取平台名称及icon
        $category = M('category')->where('id='.$info['cid'])->find();
        $info['icon'] = C('URL').$category['icon'];
        $info['cate_name'] = $category['title'];
        // 任务要求
        $money_type = $info['money_type'];
        $money_type_arr = explode(',', $money_type);
        $where2['id'] = array('in',$money_type_arr);
        $money_info = M('money_type')->where($where2)->field('title')->select();
        foreach ($money_info as $val) {
            $val = join(",",$val);
            $temp_array1[] = $val;
        }
        $info['money_info'] = implode(",", $temp_array1);
        // 发布人
        if($info['uid'] == 0){
            $info['author'] = '平台';
        }else{
            $user = M('user')->where('id='.$info['uid'])->find();
            $info['author'] = $user['nickname'];
        }
        // 任务图片
        $pics = array();
        if($info['pic'] != ''){
            $pics = explode('|', $info['pic']);
            foreach ($pics as $key=>&$value){
                $pics[$key] = C('URL').$value;
            }
        }
        
        $info['pic'] = $pics;
        
        $info['t'] = date('Y-m-d H:i:s',$info['t']);
        $this->res['data'] = $info;
        $this->response($this->res,'json');
    }
}